package com.xky.ui.module.salesManagement.add;

import com.xky.pojo.SalesOrders;
import com.xky.utils.DBUtils;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 * 添加销售订单类 - 优化版
 */
public class AddSalesOrder extends JFrame {
    
    // 定义颜色常量
    private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
    private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
    private static final Color BUTTON_COLOR = new Color(100, 149, 237);
    private static final Color SUCCESS_COLOR = new Color(46, 139, 87);
    private static final Color ERROR_COLOR = new Color(178, 34, 34);
    
    // 日期格式化
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    
    // 文本字段
    private final JTextField orderNumberField;
    private final JTextField customerIdField;
    private final JTextField orderDateField;
    private final JTextField expectedShipDateField;
    private final JTextField actualShipDateField;
    private final JTextField warehouseIdField;
    private final JComboBox<String> orderStatusComboBox;
    private final JComboBox<String> paymentStatusComboBox;
    private final JTextField subtotalField;
    private final JTextField taxAmountField;
    private final JTextField discountAmountField;
    private final JTextField totalAmountField;
    private final JTextField paidAmountField;
    private final JTextArea notesArea;
    private final JTextField createdByField;

    /**
     * 构造方法
     */
    public AddSalesOrder() {
        // 设置窗口属性
        setTitle("添加销售订单");
        setSize(500, 750);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        
        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
        mainPanel.setBackground(SECONDARY_COLOR);
        
        // 创建标题标签
        JLabel titleLabel = new JLabel("添加销售订单", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(PRIMARY_COLOR);
        titleLabel.setBorder(new EmptyBorder(0, 0, 15, 0));
        
        // 初始化文本字段
        orderNumberField = new JTextField(20);
        customerIdField = new JTextField(20);
        orderDateField = new JTextField(20);
        expectedShipDateField = new JTextField(20);
        actualShipDateField = new JTextField(20);
        warehouseIdField = new JTextField(20);
        orderStatusComboBox = new JComboBox<>(new String[]{"待处理", "已确认", "已发货", "已完成", "已取消"});
        paymentStatusComboBox = new JComboBox<>(new String[]{"未支付", "部分支付", "已支付", "已退款"});
        subtotalField = new JTextField(20);
        taxAmountField = new JTextField(20);
        discountAmountField = new JTextField(20);
        totalAmountField = new JTextField(20);
        paidAmountField = new JTextField(20);
        notesArea = new JTextArea(3, 20);
        createdByField = new JTextField(20);
        
        // 设置默认值和提示
        orderDateField.setText(LocalDate.now().format(DATE_FORMATTER));
        
        // 设置今天日期并添加自动计算总金额的焦点监听器
        setupFieldListeners();
        
        // 创建表单面板 - 使用JScrollPane包装以支持滚动
        JScrollPane scrollPane = new JScrollPane(createFormPanel());
        scrollPane.setBorder(null);
        scrollPane.getVerticalScrollBar().setUnitIncrement(16);
        
        // 创建按钮面板
        JPanel buttonPanel = createButtonPanel();
        
        // 添加组件到主面板
        mainPanel.add(titleLabel, BorderLayout.NORTH);
        mainPanel.add(scrollPane, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        // 设置内容面板
        setContentPane(mainPanel);
        
        // 显示窗口
        setVisible(true);
    }
    
    /**
     * 创建表单面板
     * @return 表单面板
     */
    private JPanel createFormPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBackground(SECONDARY_COLOR);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(8, 8, 8, 8);
        gbc.anchor = GridBagConstraints.WEST;
        
        // 创建字段标签样式
        Font labelFont = new Font("微软雅黑", Font.BOLD, 13);
        
        // 订单基本信息区域
        addSectionHeader(panel, "订单基本信息", gbc, 0);
        
        // 订单编号
        addFormField(panel, "订单编号:", orderNumberField, "必填项", gbc, 1, labelFont);
        
        // 客户ID
        addFormField(panel, "客户ID:", customerIdField, "必填项，必须为数字", gbc, 2, labelFont);
        
        // 下单日期
        addFormField(panel, "下单日期:", orderDateField, "格式: yyyy-MM-dd", gbc, 3, labelFont);
        
        // 预计发货日期
        addFormField(panel, "预计发货日期:", expectedShipDateField, "格式: yyyy-MM-dd", gbc, 4, labelFont);
        
        // 实际发货日期
        addFormField(panel, "实际发货日期:", actualShipDateField, "格式: yyyy-MM-dd", gbc, 5, labelFont);
        
        // 仓库ID
        addFormField(panel, "仓库ID:", warehouseIdField, "必填项，必须为数字", gbc, 6, labelFont);
        
        // 订单状态区域
        addSectionHeader(panel, "订单状态", gbc, 7);
        
        // 订单状态
        addFormField(panel, "订单状态:", orderStatusComboBox, null, gbc, 8, labelFont);
        
        // 支付状态
        addFormField(panel, "支付状态:", paymentStatusComboBox, null, gbc, 9, labelFont);
        
        // 财务信息区域
        addSectionHeader(panel, "财务信息", gbc, 10);
        
        // 商品总额
        addFormField(panel, "商品总额:", subtotalField, "必填项，必须为数字", gbc, 11, labelFont);
        
        // 税额
        addFormField(panel, "税额:", taxAmountField, "必填项，必须为数字", gbc, 12, labelFont);
        
        // 折扣金额
        addFormField(panel, "折扣金额:", discountAmountField, "必填项，必须为数字", gbc, 13, labelFont);
        
        // 订单总金额
        addFormField(panel, "订单总金额:", totalAmountField, "必填项，必须为数字", gbc, 14, labelFont);
        
        // 已付金额
        addFormField(panel, "已付金额:", paidAmountField, "必填项，必须为数字", gbc, 15, labelFont);
        
        // 其他信息区域
        addSectionHeader(panel, "其他信息", gbc, 16);
        
        // 备注
        gbc.gridx = 0;
        gbc.gridy = 17;
        JLabel notesLabel = new JLabel("备注:");
        notesLabel.setFont(labelFont);
        panel.add(notesLabel, gbc);
        
        gbc.gridx = 1;
        notesArea.setLineWrap(true);
        notesArea.setWrapStyleWord(true);
        JScrollPane notesScrollPane = new JScrollPane(notesArea);
        notesScrollPane.setPreferredSize(new Dimension(300, 80));
        panel.add(notesScrollPane, gbc);

        
        return panel;
    }
    
    /**
     * 创建按钮面板
     * @return 按钮面板
     */
    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        panel.setBackground(SECONDARY_COLOR);
        
        // 创建保存按钮
        JButton saveButton = createStyledButton("保存", BUTTON_COLOR);
        saveButton.addActionListener(e -> saveSalesOrder());
        
        // 创建取消按钮
        JButton cancelButton = createStyledButton("取消", Color.LIGHT_GRAY);
        cancelButton.addActionListener(e -> dispose());
        
        // 创建重置按钮
        JButton resetButton = createStyledButton("重置", new Color(220, 20, 60));
        resetButton.addActionListener(e -> resetForm());
        
        // 添加按钮到面板
        panel.add(saveButton);
        panel.add(resetButton);
        panel.add(cancelButton);
        
        return panel;
    }
    
    /**
     * 创建样式化按钮
     * @param text 按钮文本
     * @param bgColor 背景颜色
     * @return 样式化按钮
     */
    private JButton createStyledButton(String text, Color bgColor) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.BOLD, 14));
        button.setPreferredSize(new Dimension(100, 38));
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));
        return button;
    }
    
    /**
     * 添加表单字段
     * @param panel 面板
     * @param labelText 标签文本
     * @param component 组件
     * @param tooltip 提示文本
     * @param gbc 网格包约束
     * @param gridY 网格Y坐标
     * @param labelFont 标签字体
     */
    private void addFormField(JPanel panel, String labelText, JComponent component, 
                             String tooltip, GridBagConstraints gbc, int gridY, Font labelFont) {
        gbc.gridx = 0;
        gbc.gridy = gridY;
        JLabel label = new JLabel(labelText);
        label.setFont(labelFont);
        panel.add(label, gbc);
        
        gbc.gridx = 1;
        if (component instanceof JTextField) {
            JTextField textField = (JTextField) component;
            textField.setBorder(BorderFactory.createCompoundBorder(
                textField.getBorder(), 
                BorderFactory.createEmptyBorder(5, 5, 5, 5)
            ));
            
            if (tooltip != null) {
                textField.setToolTipText(tooltip);
            }
        }
        panel.add(component, gbc);
    }
    
    /**
     * 添加分区标题
     * @param panel 面板
     * @param title 标题
     * @param gbc 网格包约束
     * @param gridY 网格Y坐标
     */
    private void addSectionHeader(JPanel panel, String title, GridBagConstraints gbc, int gridY) {
        gbc.gridx = 0;
        gbc.gridy = gridY;
        gbc.gridwidth = 2;
        
        JLabel sectionLabel = new JLabel(title);
        sectionLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        sectionLabel.setForeground(PRIMARY_COLOR);
        sectionLabel.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createMatteBorder(0, 0, 1, 0, PRIMARY_COLOR),
            BorderFactory.createEmptyBorder(5, 0, 5, 0)
        ));
        
        panel.add(sectionLabel, gbc);
        
        // 重置网格宽度
        gbc.gridwidth = 1;
    }
    
    /**
     * 设置字段监听器
     */
    private void setupFieldListeners() {
        // 焦点监听器，用于自动计算总金额
        FocusAdapter amountCalculator = new FocusAdapter() {
            @Override
            public void focusLost(FocusEvent e) {
                calculateTotalAmount();
            }
        };
        
        // 添加焦点监听器到金额字段
        subtotalField.addFocusListener(amountCalculator);
        taxAmountField.addFocusListener(amountCalculator);
        discountAmountField.addFocusListener(amountCalculator);
    }
    
    /**
     * 计算订单总金额
     */
    private void calculateTotalAmount() {
        try {
            // 获取各个金额字段的值
            BigDecimal subtotal = getDecimalValue(subtotalField.getText(), BigDecimal.ZERO);
            BigDecimal taxAmount = getDecimalValue(taxAmountField.getText(), BigDecimal.ZERO);
            BigDecimal discountAmount = getDecimalValue(discountAmountField.getText(), BigDecimal.ZERO);
            
            // 计算总金额: subtotal + taxAmount - discountAmount
            BigDecimal totalAmount = subtotal.add(taxAmount).subtract(discountAmount);
            
            // 更新总金额字段
            totalAmountField.setText(totalAmount.toString());
        } catch (NumberFormatException e) {
            // 忽略非数字输入
        }
    }
    
    /**
     * 获取BigDecimal值，如果转换失败则返回默认值
     * @param text 文本
     * @param defaultValue 默认值
     * @return BigDecimal值
     */
    private BigDecimal getDecimalValue(String text, BigDecimal defaultValue) {
        if (text == null || text.trim().isEmpty()) {
            return defaultValue;
        }
        try {
            return new BigDecimal(text.trim());
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }
    
    /**
     * 重置表单
     */
    private void resetForm() {
        // 重置所有字段
        orderNumberField.setText("");
        customerIdField.setText("");
        orderDateField.setText(LocalDate.now().format(DATE_FORMATTER));
        expectedShipDateField.setText("");
        actualShipDateField.setText("");
        warehouseIdField.setText("");
        orderStatusComboBox.setSelectedIndex(0);
        paymentStatusComboBox.setSelectedIndex(0);
        subtotalField.setText("");
        taxAmountField.setText("");
        discountAmountField.setText("");
        totalAmountField.setText("");
        paidAmountField.setText("");
        notesArea.setText("");
    }
    
    /**
     * 保存销售订单
     */
    private void saveSalesOrder() {
        // 验证输入
        if (!validateInput()) {
            return;
        }
        
        try {
            // 构造销售订单对象
            SalesOrders order = constructSalesOrder();
            
            // 保存到数据库
            if (insertSalesOrder(order)) {
                showMessage("销售订单添加成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } else {
                showMessage("销售订单添加失败！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception e) {
            showMessage("发生错误: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
    }
    
    /**
     * 显示消息对话框
     * @param message 消息
     * @param title 标题
     * @param messageType 消息类型
     */
    private void showMessage(String message, String title, int messageType) {
        JOptionPane.showMessageDialog(this, message, title, messageType);
    }
    
    /**
     * 验证输入
     * @return 验证结果
     */
    private boolean validateInput() {
        // 验证订单编号
        if (orderNumberField.getText().trim().isEmpty()) {
            showMessage("请输入订单编号！", "输入错误", JOptionPane.ERROR_MESSAGE);
            orderNumberField.requestFocus();
            return false;
        }
        
        // 验证客户ID
        try {
            Integer.parseInt(customerIdField.getText().trim());
        } catch (NumberFormatException e) {
            showMessage("客户ID必须是数字！", "输入错误", JOptionPane.ERROR_MESSAGE);
            customerIdField.requestFocus();
            return false;
        }
        
        // 验证下单日期
        try {
            LocalDate.parse(orderDateField.getText().trim(), DATE_FORMATTER);
        } catch (DateTimeParseException e) {
            showMessage("下单日期格式不正确，请使用yyyy-MM-dd格式！", "输入错误", JOptionPane.ERROR_MESSAGE);
            orderDateField.requestFocus();
            return false;
        }
        
        // 验证预计发货日期
        if (!expectedShipDateField.getText().trim().isEmpty()) {
            try {
                LocalDate.parse(expectedShipDateField.getText().trim(), DATE_FORMATTER);
            } catch (DateTimeParseException e) {
                showMessage("预计发货日期格式不正确，请使用yyyy-MM-dd格式！", "输入错误", JOptionPane.ERROR_MESSAGE);
                expectedShipDateField.requestFocus();
                return false;
            }
        }
        
        // 验证实际发货日期
        if (!actualShipDateField.getText().trim().isEmpty()) {
            try {
                LocalDate.parse(actualShipDateField.getText().trim(), DATE_FORMATTER);
            } catch (DateTimeParseException e) {
                showMessage("实际发货日期格式不正确，请使用yyyy-MM-dd格式！", "输入错误", JOptionPane.ERROR_MESSAGE);
                actualShipDateField.requestFocus();
                return false;
            }
        }
        
        // 验证仓库ID
        try {
            Integer.parseInt(warehouseIdField.getText().trim());
        } catch (NumberFormatException e) {
            showMessage("仓库ID必须是数字！", "输入错误", JOptionPane.ERROR_MESSAGE);
            warehouseIdField.requestFocus();
            return false;
        }
        
        // 验证金额字段
        String[] amountFields = {
            subtotalField.getText().trim(),
            taxAmountField.getText().trim(),
            discountAmountField.getText().trim(),
            totalAmountField.getText().trim(),
            paidAmountField.getText().trim()
        };
        
        String[] fieldNames = {
            "商品总额", "税额", "折扣金额", "订单总金额", "已付金额"
        };
        
        JTextField[] fields = {
            subtotalField, taxAmountField, discountAmountField,
            totalAmountField, paidAmountField
        };
        for (int i = 0; i < amountFields.length; i++) {
            try {
                new BigDecimal(amountFields[i]);
            } catch (NumberFormatException e) {
                showMessage(fieldNames[i] + "必须是有效的数字！", "输入错误", JOptionPane.ERROR_MESSAGE);
                fields[i].requestFocus();
                return false;
            }
        }

        return true;
    }
    
    /**
     * 构造销售订单对象
     * @return 销售订单对象z
     */
    private SalesOrders constructSalesOrder() {
        SalesOrders order = new SalesOrders();
        
        order.setOrderNumber(orderNumberField.getText().trim());
        order.setCustomerId(Integer.parseInt(customerIdField.getText().trim()));
        
        // 设置日期和时间
        LocalDateTime orderTime = LocalDate.parse(orderDateField.getText().trim(), DATE_FORMATTER).atStartOfDay();
        order.setOrderDate(orderTime);
        
        if (!expectedShipDateField.getText().trim().isEmpty()) {
            LocalDate expectedShipDate = LocalDate.parse(expectedShipDateField.getText().trim(), DATE_FORMATTER);
            order.setExpectedShipDate(expectedShipDate);
        }
        
        if (!actualShipDateField.getText().trim().isEmpty()) {
            LocalDate actualShipDate = LocalDate.parse(actualShipDateField.getText().trim(), DATE_FORMATTER);
            order.setActualShipDate(actualShipDate);
        }
        
        order.setWarehouseId(Integer.parseInt(warehouseIdField.getText().trim()));
        
        // 根据选择的订单状态设置订单状态代码
        String orderStatusText = (String) orderStatusComboBox.getSelectedItem();
        String orderStatusCode = convertOrderStatusToCode(orderStatusText);
        order.setOrderStatus(orderStatusCode);
        
        // 根据选择的支付状态设置支付状态代码
        String paymentStatusText = (String) paymentStatusComboBox.getSelectedItem();
        String paymentStatusCode = convertPaymentStatusToCode(paymentStatusText);
        order.setPaymentStatus(paymentStatusCode);
        
        order.setSubtotal(new BigDecimal(subtotalField.getText().trim()));
        order.setTaxAmount(new BigDecimal(taxAmountField.getText().trim()));
        order.setDiscountAmount(new BigDecimal(discountAmountField.getText().trim()));
        order.setTotalAmount(new BigDecimal(totalAmountField.getText().trim()));
        order.setPaidAmount(new BigDecimal(paidAmountField.getText().trim()));
        order.setNotes(notesArea.getText().trim());
        
        if (!createdByField.getText().trim().isEmpty()) {
            order.setCreatedBy(Integer.parseInt(createdByField.getText().trim()));
        }
        
        order.setCreatedTime(LocalDateTime.now());
        order.setUpdatedTime(LocalDateTime.now());
        
        return order;
    }
    
    /**
     * 将订单状态文本转换为代码
     * @param statusText 状态文本
     * @return 状态代码
     */
    private String convertOrderStatusToCode(String statusText) {
        switch (statusText) {
            case "待处理": return "PENDING";
            case "已确认": return "CONFIRMED";
            case "已发货": return "SHIPPED";
            case "已完成": return "COMPLETED";
            case "已取消": return "CANCELLED";
            default: return "PENDING";
        }
    }
    
    /**
     * 将支付状态文本转换为代码
     * @param statusText 状态文本
     * @return 状态代码
     */
    private String convertPaymentStatusToCode(String statusText) {
        switch (statusText) {
            case "未支付": return "UNPAID";
            case "部分支付": return "PARTIAL";
            case "已支付": return "PAID";
            case "已退款": return "REFUNDED";
            default: return "UNPAID";
        }
    }
    
    /**
     * 插入销售订单到数据库
     * @param order 销售订单对象
     * @return 是否成功
     */
    private boolean insertSalesOrder(SalesOrders order) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = DBUtils.getConnection();
            
            String sql = "INSERT INTO sales_orders (order_number, customer_id, order_date, expected_ship_date, " +
                         "actual_ship_date, warehouse_id, order_status, payment_status, " +
                         "subtotal, tax_amount, discount_amount, total_amount, paid_amount, " +
                         "notes, created_time, updated_time) " +
                         "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            pstmt = conn.prepareStatement(sql);
            int index = 1;
            pstmt.setString(index++, order.getOrderNumber());
            pstmt.setInt(index++, order.getCustomerId());
            pstmt.setTimestamp(index++, Timestamp.valueOf(order.getOrderDate()));
            
            if (order.getExpectedShipDate() != null) {
                pstmt.setDate(index++, java.sql.Date.valueOf(order.getExpectedShipDate()));
            } else {
                pstmt.setNull(index++, java.sql.Types.DATE);
            }
            
            if (order.getActualShipDate() != null) {
                pstmt.setDate(index++, java.sql.Date.valueOf(order.getActualShipDate()));
            } else {
                pstmt.setNull(index++, java.sql.Types.DATE);
            }
            
            pstmt.setInt(index++, order.getWarehouseId());
            pstmt.setString(index++, order.getOrderStatus());
            pstmt.setString(index++, order.getPaymentStatus());
            pstmt.setBigDecimal(index++, order.getSubtotal());
            pstmt.setBigDecimal(index++, order.getTaxAmount());
            pstmt.setBigDecimal(index++, order.getDiscountAmount());
            pstmt.setBigDecimal(index++, order.getTotalAmount());
            pstmt.setBigDecimal(index++, order.getPaidAmount());
            pstmt.setString(index++, order.getNotes());
            pstmt.setTimestamp(index++, Timestamp.valueOf(order.getCreatedTime()));
            pstmt.setTimestamp(index++, Timestamp.valueOf(order.getUpdatedTime()));
            
            int rowsAffected = pstmt.executeUpdate();
            return rowsAffected > 0;
            
        } catch (SQLException e) {
            e.printStackTrace();
            showMessage("数据库错误: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            return false;
        } finally {
            DBUtils.closeAll(conn, pstmt, null);
        }
    }
    
    /**
     * 主方法，用于测试
     */
    public static void main(String[] args) {
        try {
            // 使用系统外观
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        // 启动应用程序
        SwingUtilities.invokeLater(AddSalesOrder::new);
    }
} 